<?php

/**
 * Albireo Kernel
 *
 * @copyright  Copyright (c) 2010 Albireo Solutions
 * @package    Kernel
 */

namespace Albireo\RemoteServer;

use \Nette\Object;


/**
 * Albireo class simplyfing communication with remote servers
 *
 * @author     Albireo Solutions
 * @package    Kernel
 */
class RemoteCommunication extends Object {

    private $url;

    /**
     * register remote server url
     * @param URL $url remote server url
     */
    public function __construct ( $url ) {
	$this -> url = $url;
    }

    /**
     * gets remote server headers
     * @throws MalformedURLException
     * @return mixed returns header string or false on communication error
     */
    public function getHeaders () {
	$url_p = parse_url ( $this -> url );

	if ( isset ( $url_p [ "host" ] ) ){
	    $host = $url_p["host"];
	} else {
	    throw new MalformedURLException();
	    return FALSE;
	}

	if ( isset ( $url_p [ "path" ] ) ) {
	    $path = $url_p["path"];
	} else {
	    $path = "";
	}

	$port = ( isset ( $url_p [ "port" ] ) ) ? $url_p [ "port" ] : 80;

	$fp = @fsockopen ($host, $port, $errno, $errstr, 20);
	if ( !$fp ) {
	    return FALSE;
	} else {
	    $parse = parse_url ( $this -> url );

	    if ($fp) @fputs($fp, "HEAD ".$this -> url." http/1.1\r\n");
	    if ($fp) @fputs($fp, "HOST: ".$host."\r\n");
	    if ($fp) @fputs($fp, "Connection: close\r\n\r\n");
	    $headers = "";
	    while (!feof ($fp)) {
		$headers .= fgets ($fp, 128);
	    }
	}
	fclose ($fp);
	return htmlentities ( $headers );
    }

    /**
     * checks whether remote url exists and returns http header 200
     * @throws MalformedURLException
     * @return boolean
     */
    public function exists () {
	try {
	    $headers = $this -> getHeaders();
	} catch (MalformedURLException $e) {
	    throw new MalformedURLException();
	    return FALSE;
	}
	if(strstr($headers, "200 OK")) {
	    return TRUE;
	} else {
	    return FALSE;
	}
    }
    
}